<?php

namespace addons\shop\controller\api;

use addons\shop\model\Order;
use think\Config;
use think\Db;


/**
 * 会员
 */
class User extends Base
{
    protected $noNeedLogin = ['getSigned','appupdate'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 个人中心
     */
    public function index()
    {
        $apptype = $this->request->param('apptype');
        $platform = $this->request->param('platform');
        $logincode = $this->request->param('logincode');

        $info = $this->auth->getUserInfo();
        $info['shopping_integral'] = $this->auth->getUser()->shopping_integral;
        $info['coupon_integral'] = $this->auth->getUser()->coupon_integral;
        $info['money'] = $this->auth->getUser()->money;
        $info['promotion_bonus'] = $this->auth->getUser()->promotion_bonus;
        $info['green_integral'] = $this->auth->getUser()->green_integral;
        $info['team_level'] = $this->auth->getUser()->team_level;
        $info['yeji_team'] = $this->auth->getUser()->yeji_team;

        $info['order'] = [
            'created'  => Order::where('user_id', $this->auth->id)->where('orderstate', 0)->where('paystate', 0)->count(),
            'paid'     => Order::where('user_id', $this->auth->id)->where('orderstate', 0)->where('paystate', 1)->where('shippingstate', 0)->count(),
            'evaluate' => Order::where('user_id', $this->auth->id)->where('orderstate', 0)->where('paystate', 1)->where('shippingstate', 2)->count()
        ];
        $info['avatar'] = cdnurl($info['avatar'], true);
        $signin = get_addon_info('signin');
        $info['is_install_signin'] = ($signin && $signin['state']);

        $firstlogin = $this->auth->jointime === $this->auth->logintime;

        //判断是否显示昵称更新提示
        $profilePrompt = false;
        $config = get_addon_config('shop');
        if ($config['porfilePrompt'] === 'firstlogin') {
            $profilePrompt = $this->auth->jointime === $this->auth->logintime;
        } elseif ($config['porfilePrompt'] === 'everylogin') {
            $profilePrompt = true;
        } elseif ($config['porfilePrompt'] === 'disabled') {
            $profilePrompt = false;
        }
        $showProfilePrompt = false;
        if ($profilePrompt) {
            $showProfilePrompt = !$info['nickname'] || stripos($info['nickname'], '微信用户') !== false || preg_match("/^\d{3}\*{4}\d{4}$/", $info['nickname']);
        }

        $openid = '';
        //如果有传登录code，则获取openid
        if ($logincode) {
            $json = (new \addons\shop\library\Wechat\Service())->getWechatSession($logincode);
            $openid = $json['openid'] ?? '';
        }
        $data['openid'] = $openid;

        $this->success('', [
            'userInfo' => $info,
            'openid'            => $openid,
            'showProfilePrompt' => $showProfilePrompt
        ]);
    }


    /**
     * 个人资料
     */
    public function profile()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar');
        if (!$username || !$nickname) {
            $this->error("用户名和昵称不能为空");
        }
        if (strlen($bio) > 100) {
            $this->error("签名太长了！");
        }
        $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        if ($exists) {
            $this->error(__('Username already exists'));
        }

        $avatar = str_replace(cdnurl('', true), '', $avatar);

        $user->username = $username;
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();

        $this->success('修改成功！');
    }

    /**
     * 保存头像
     */
    public function avatar()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }
        $user = $this->auth->getUser();
        $avatar = $this->request->post('avatar');
        if (!$avatar) {
            $this->error("头像不能为空");
        }

        $avatar = str_replace(cdnurl('', true), '', $avatar);
        $user->avatar = $avatar;
        $user->save();
        $this->success('修改成功！');
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'), ['__token__' => $this->request->token()]);
    }

    /**
     * 分享配置参数
     */
    public function getSigned()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }
        $url = $this->request->param('url', '', 'trim');
        $js_sdk = new \addons\shop\library\Jssdk();
        $data = $js_sdk->getSignedPackage($url);
        $this->success('', $data);
    }



    
    /**
     * 生成推广码，格式：3位随机字符串+user_id
     * @param int $userId 用户ID
     * @return string 推广码
     */
    private function generateReferralCode($userId)
    {
        do {
            // 生成3位随机字符串（大写字母）
            $randomStr = '';
            $chars = 'abcdefghijkmnopqrstuvwxyz';
            for ($i = 0; $i < 3; $i++) {
                $randomStr .= $chars[mt_rand(0, strlen($chars) - 1)];
            }
            
            // 格式：3位随机字符串+user_id
            $tui_code = $randomStr . $userId;
            
            // 检查是否重复
            $exists = \app\common\model\User::where('tui_code', $tui_code)->find();
        } while ($exists);
        
        return $tui_code;
    }

    /**
     * 获取推广码和推广海报
     */
    public function poster()
    {
        $user = $this->auth->getUser();
        
        // 如果没有推广码，则生成一个
        if (empty($user->tui_code)) {
            $user->tui_code = $this->generateReferralCode($user->id);
            $user->save();
        }

        // 生成带推广码的海报图片
        $posterImageUrl = $this->generatePosterWithCode($user->tui_code, $user->id);
        
        $this->success('', [
            'poster_url' => $posterImageUrl,
            'tui_code' => $user->tui_code,
        ]);
    }

    /**
     * 生成带推广码的海报图片
     * @param string $tuiCode 推广码
     * @param int $userId 用户ID
     * @return string 生成的图片URL
     */
    private function generatePosterWithCode($tuiCode, $userId)
    {
        try {
            // 原始海报图片路径
            $originalImagePath = ROOT_PATH . 'public/assets/img/tuiguang.jpg';
            
            // 检查原始图片是否存在
            if (!file_exists($originalImagePath)) {
                return '';
            }
            
            // 创建图片资源
            $imageInfo = getimagesize($originalImagePath);
            $imageType = $imageInfo[2];
            
            switch ($imageType) {
                case IMAGETYPE_JPEG:
                    $image = imagecreatefromjpeg($originalImagePath);
                    break;
                case IMAGETYPE_PNG:
                    $image = imagecreatefrompng($originalImagePath);
                    break;
                case IMAGETYPE_GIF:
                    $image = imagecreatefromgif($originalImagePath);
                    break;
                default:
                    return '';
            }
            
            if (!$image) {
                return '';
            }
            
            // 设置文字颜色（黑色）
            $textColor = imagecolorallocate($image, 0, 0, 0);
            
            // 获取图片尺寸
            $imageWidth = imagesx($image);
            $imageHeight = imagesy($image);
            
            // 设置文字内容
            $text = "推广码: {$tuiCode}";
            
            
            // 1. 指定TTF字体文件路径
            $fontFile = ROOT_PATH . 'public/assets/fonts/simhei.ttf';
            
            // 2. 检查字体文件是否存在
            if (!file_exists($fontFile)) {
                // 备选字体（根据服务器实际情况调整）
                $fontFile = '/usr/share/fonts/truetype/wqy/wqy-microhei.ttc'; // Linux系统示例
                if (!file_exists($fontFile)) {
                    throw new \Exception('未找到字体文件，请配置正确的TTF字体路径');
                }
            }
            
            // 3. 设置字体大小
            $fontSize = 48; // 字体大小，数值越大文字越大
            
            // 4. 计算文字位置（居中底部，根据实际图片尺寸调整）
            // 先计算文字宽度和高度
            $textBox = imagettfbbox($fontSize, 0, $fontFile, $text);
            $textWidth = $textBox[2] - $textBox[0]; // 文字宽度
            $textHeight = $textBox[1] - $textBox[7]; // 文字高度
            
            // 居中显示（水平居中，垂直位置可调整）
            $textX = ($imageWidth - $textWidth) / 2;
            $textY = 600;
            
            // 5. 绘制文字（使用TTF字体）
            imagettftext($image, $fontSize, 0, $textX, $textY, $textColor, $fontFile, $text);
            
            // 生成新的文件名
            $newImageName = 'tuiguang_' . $userId . '_' . time() . '.jpg';
            $newImagePath = ROOT_PATH . 'public/qrcode/' . $newImageName;
            
            // 确保目录存在
            if (!is_dir(dirname($newImagePath))) {
                mkdir(dirname($newImagePath), 0755, true);
            }
            
            // 保存新图片
            $success = imagejpeg($image, $newImagePath, 90);
            
            // 释放内存
            imagedestroy($image);

            // 使用配置文件中的url
            // $poster_url = \think\Config::get('url') . 'qrcode/' . $newImageName;
            // 插件配置
            $shopConfig = get_addon_config('shop');
            $poster_url = $shopConfig['mobileurl'] . 'qrcode/' . $newImageName;

            
            return $success ? $poster_url : '';
            
        } catch (\Exception $e) {
            \think\Log::error('生成推广海报失败: ' . $e->getMessage());
            return '';
        }
    }


    // 获取业绩日志
    public function yejilogs()
    { 
        $list = \app\admin\model\user\Yejilog::where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->paginate(10);

        $this->success('', $list);
    }

    // 获取推广关系数据
    // 查询上级，查询当前用户zhitui_id
    // 查询下级，查询用户表 zhitui_id是当前用户id的用户 
    public function getTuiguangData()
    {
        $user = $this->auth->getUser();
        $data = [
            'superior' => \app\admin\model\User::where(['id' => $user->zhitui_id])->field('username,tui_code as id')->find(),

            'subordinates' => \app\admin\model\User::where(['zhitui_id' => $this->auth->id])->field('username,tui_code as id')->select(),
        ];
        $this->success('', $data);
    }


    public function appupdate()
    { 
        $param = $this->request->param();
        $app_version = Db::name('config')->where(['name' => 'app_version'])->value('value');

        $url = get_addon_config('shop')['mobileurl'];

        // 判断是否需要升级
        if ($param['version']!=$app_version) {
            $this->success('', [
                // 1：需要升级；0：无需升级
                'status' => 1,
                'note' => '升级优化部分内容，点击安装新版本',
                'url' => $url.'download/index/app.apk',
                // 'url' => 'http://103.120.82.83:8081/download/index/index.html'
            ]);
        }else{
            $this->success('', [
                // 0：无需升级
                'status' => 0,
                'note' => '升级优化部分内容，点击安装新版本',
                'url' => $url.'download/index/app.apk',
            ]);
        }
        

        
    }


}
